<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>SpringMVC 解毒1 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解毒1</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-12T08:30:00+00:00">2018-08-12</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/12/learn-springmvc-code-1/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/12/learn-springmvc-code-1/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/12/learn-springmvc-code-1/" class="leancloud_visitors" data-flag-title="SpringMVC 解毒1">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="0-前言"><a href="#0-前言" class="headerlink" title="0 前言"></a>0 前言</h2><p>学Java开发的同学始终避不开Spring，学JavaWeb开发的同学就更避不开SpringMVC了。凡是有点追求的程序员肯定也想读一读Spring和SpringMVC的源码，我也不例外，做JavaWeb开发有两年多了，平时开发中也有debug进SpringMVC源码，但始终没有对SpringMVC源码有一个整体的、全面的了解。这次，我将带着读者一览SpringMVC，将它的核心流程和边边角角尽量清楚地展示给大家，为什么起名SpringMVC 解毒，其含义是：在这里，一次的、全面的了解SpringMVC，然后似庖丁解牛般使用SpringMVC而设计你的业务。我阅读的源码是基于<code>4.3.0.RELEASE</code>版本，读者如果想看到同样的代码和效果，也请采用该版本。</p>
<a id="more"></a>

<p>Spring是应用于企业级Java程序开发的框架，它提供了控制反转（IOC）、面向切面编程、对象生命周期管理等一系列特性。而SpringMVC是基于Spring的JavaWeb开发框架，可以这么说，只使用Spring核心框架也可以进行web开发，但SpringMVC可以让你把精神集中在业务代码开发，而不是各种协议异常处理。</p>
<p>以下是我在阅读源码时整理的类图关系。</p>
<p>=================此处应有图，然而图太大了，根本看不清=============</p>
<p>这张图实际上并没有展示SpringMVC框架中所有类，只有常用的一些。刚看到这张图谁都会懵，但是我想当你阅读完所有文章后，回头再看这张图，也会会心一笑。解读框架的逻辑是先从主要入口类着手，然后针对入口类中使用到的的每个接口分别再详细展开，在接口实现类中如又遇到接口，之后再会对接口详细展开。这一系列文章不会对Spring的bean管理着墨太多，如果想顺利地阅读，我希望你有这些基础：Servlet规范，SpringBeanDefinition解析，SpringBean容器初始化等，如果没有的话，你可能阅读起来很吃力，不过可以参考我写的其他文章。</p>
<h2 id="1-MVC-简介"><a href="#1-MVC-简介" class="headerlink" title="1 MVC 简介"></a>1 MVC 简介</h2><p>MVC 是一种设计模式，它能够让项目组织架构变得比较合理，适合阅读与理解。</p>
<img src="http://www.plantuml.com/plantuml/svg/RL0zJm914EttL-mViF2Zeh2njjJ6M13OIqZEMtESsXf3o2K6n71W47EemK0bXp4YcE2VSURkPpYxGn0IjzdTD_FclNcYv0NAT_859TDeYE7aeAnycI_BCxg5E99O7q3u0PtXdlO2NxikbOzDGs7v5yBJWPA1FfNQMSKb7PZVGPZmx6mqmV6LXR7rdZQg360hmThhpwoFmoU8hw5VeHAJaofZsNS4tJYzhonxqw_EUKbTGEEMP-Fd6_QQGdb5QTnOwvQwhujvbosVcEUwMuQirdCCuID6K-oziChQi6nGXUxya2HvbX4NT4nEScDtPMsPavkBJSKAIZrMZCfRMNq2DsrykCHsmbhiTPr03AD2X6qcm6WAiuYT265hr6CTvEGEPmJD6lKibdIL4vWjhLaRkqq9ngsqF_itsR-TVm40">


<p>JavaWeb开发自Servlet规范出现，最开始是直接继承Servlet进行开发，需要向用户返回数据时，直接向outputstream写字符串。然后出现了JSP技术，以前是在Java代码里写html，JSP就是在html里写java，JSP定义了一系列的标签，允许在html代码里加入Java代码，运行时再编译成Servlet再运行。也就是说你写的Servlet项目只需要容器能够解析Servlet，而如果写的JSP，则需要容器能够编译JSP。如果业务URI较多，一般会有多个Servlet或JSP，显然，这两种开发方式对快速业务开发不合适。</p>
<p>SpringMVC是怎样解决上述问题的呢？SpringMVC提供了一个统一的Servlet实现类来接管用户的Servlet，然后允许使用者通过配置的方式指定URI与具体实现方法之间的关系。使用者只管写Java代码，而不需要管http字符流如何解析为方法入参，返回值如何解析为http字符流。</p>
<img src="http://www.plantuml.com/plantuml/svg/TLFBJi905DtFLymFTE4xCOR4k79heXlZWa1H4cnDhRBrYHZ3m_2AOl25maAnFa6C-ZFSQVaBP-PYfO1DccRctdFFEVVUah1cgaR87r2fdQsoU7r-NJMeVvrky2yXYnGE4_PdZIKh47-3aofT4i6GeMlc37yDFH8HUPfkgjJKrwWUwWjI_ZYLQrPApy_DobDxwzJvFk2dLYD9tTAm_sm_VxJt1Hzy5I1kkQ6k6d1ViEzksUjsgz7iWjv0QWUph5rXP03I-Sv2iSJpMCxYOBSGKRKW5GQ4tHwZWNyy1hpsK2usq7ceiqVKmd8lTZg65voK9MgjPfbLBw5q1EKz7aAm5SCx56YVxhcvziV9PbYDGleOQxF64plFU0LBAAfTrOF-I4TeH0sPGYdUIPwh4iGlMFQTdTyWWwUGKub1yGiB2LB27x44L372ookcukiTB9saGto67R-aD-h20js8uTxvaAwm4jIZ6aT8pJnvn4dM8PLdPriiRw5ajDlFDgK8mugNR1GxAijDQy45wQfFPuTKUEQOCLnEYS5sOsC8aGdAnjh0JepZ2a0c0SrifxlzL5AZJ_vRb8CcCFstWzx1oHd8BP8gu35dbvi35-LlZ3y0">


<h2 id="2-DispatcherServlet"><a href="#2-DispatcherServlet" class="headerlink" title="2 DispatcherServlet"></a>2 DispatcherServlet</h2><img src="http://www.plantuml.com/plantuml/svg/ZP3B3e8m44NtVCM4fGaaxes9px3HXIRknp9Y8vPcMiL4_NT159LYjCkUSwVJwsaKEqm8Cav2ercgPCEufppZNPZJEZJ4nvGid3qFYeDhOnc5XSXQlQpOa50rwFGvuw5KMAHe38obqMZ5blW3IcM9DoW88bHnIZn3hOjrxh3T6CIeYwisOoKfNv39qcCxVqoOd0HfApDLks-BrWw9G-cCjYZLQrYZ0UXTWi3zUAqtIUMxPTG11u7VzQ4J17tmv_xNblwBETNzYBNt-TzRRibb_khT0000">

<p><code>DispatcherServlet</code>是前一章中提到的前置控制器，接管了之前需要用户写的Servlet。要了解 <code>DispatcherServlet</code> 就要了解它的父类。我们就从 <code>HttpServletBean</code> 开始吧。’</p>
<h3 id="2-1-HttpServletBean分析"><a href="#2-1-HttpServletBean分析" class="headerlink" title="2.1 HttpServletBean分析"></a>2.1 HttpServletBean分析</h3><p><code>HttpServletBean</code> 继承了 <code>javax.servlet.http.HttpServlet</code> ，这里就不详述了。我们都知道，Servlet的生命周期自init方法，期间通过service方法响应请求，而在程序关闭时会调用destroy方法，在 <code>HttpServletBean</code> 中，他实现了init方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Map config parameters onto bean properties of this servlet, and</span></span><br><span class="line"><span class="comment"> * invoke subclass initialization.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ServletException if bean properties are invalid (or required</span></span><br><span class="line"><span class="comment"> * properties are missing), or if subclass initialization fails.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Initializing servlet '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Set bean properties from init parameters.</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        PropertyValues pvs = <span class="keyword">new</span> ServletConfigPropertyValues(getServletConfig(), <span class="keyword">this</span>.requiredProperties);</span><br><span class="line">        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(<span class="keyword">this</span>);</span><br><span class="line">        ResourceLoader resourceLoader = <span class="keyword">new</span> ServletContextResourceLoader(getServletContext());</span><br><span class="line">        bw.registerCustomEditor(Resource<span class="class">.<span class="keyword">class</span>, <span class="title">new</span> <span class="title">ResourceEditor</span>(<span class="title">resourceLoader</span>, <span class="title">getEnvironment</span>()))</span>;</span><br><span class="line">        initBeanWrapper(bw);</span><br><span class="line">        bw.setPropertyValues(pvs, <span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (BeansException ex) &#123;</span><br><span class="line">        logger.error(<span class="string">"Failed to set bean properties on servlet '"</span> + getServletName() + <span class="string">"'"</span>, ex);</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Let subclasses do whatever initialization they like.</span></span><br><span class="line">    initServletBean();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Servlet '"</span> + getServletName() + <span class="string">"' configured successfully"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subclasses may override this to perform custom initialization.</span></span><br><span class="line"><span class="comment"> * All bean properties of this servlet will have been set before this</span></span><br><span class="line"><span class="comment"> * method is invoked.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This default implementation is empty.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ServletException if subclass initialization fails</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initServletBean</span><span class="params">()</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个init方法中，做了一些资源处理，最重要的是给我们留下了一个空方法initServletBean，看这个名字就知道应该是要在这个方法里初始化ServletBean的。</p>
<h3 id="2-2-FrameworkServlet分析"><a href="#2-2-FrameworkServlet分析" class="headerlink" title="2.2 FrameworkServlet分析"></a>2.2 FrameworkServlet分析</h3><h4 id="2-2-1-FrameworkServlet初始化分析"><a href="#2-2-1-FrameworkServlet初始化分析" class="headerlink" title="2.2.1 FrameworkServlet初始化分析"></a>2.2.1 FrameworkServlet初始化分析</h4><p>看完<code>HttpServletBean</code>，接下来就该它的子类 <code>FrameworkServlet</code>了。果不其然，果真实现了initServletBean方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Overridden method of &#123;<span class="doctag">@link</span> HttpServletBean&#125;, invoked after any bean properties</span></span><br><span class="line"><span class="comment"> * have been set. Creates this servlet's WebApplicationContext.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">initServletBean</span><span class="params">()</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">    getServletContext().log(<span class="string">"Initializing Spring FrameworkServlet '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isInfoEnabled()) &#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"FrameworkServlet '"</span> + getServletName() + <span class="string">"': initialization started"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.webApplicationContext = initWebApplicationContext();</span><br><span class="line">        initFrameworkServlet();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (ServletException ex) &#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.error(<span class="string">"Context initialization failed"</span>, ex);</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (RuntimeException ex) &#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.error(<span class="string">"Context initialization failed"</span>, ex);</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isInfoEnabled()) &#123;</span><br><span class="line">        <span class="keyword">long</span> elapsedTime = System.currentTimeMillis() - startTime;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"FrameworkServlet '"</span> + getServletName() + <span class="string">"': initialization completed in "</span> +</span><br><span class="line">                elapsedTime + <span class="string">" ms"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>饭要慢慢吃，这个类代码虽多，但是不要着急。这个实现方法做了两件事，一个是初始化web应用上下文和初始化框架servlet，另一个是统计初始化时间。</p>
<p>先看初始化web应用上下文吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize and publish the WebApplicationContext for this servlet.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Delegates to &#123;<span class="doctag">@link</span> #createWebApplicationContext&#125; for actual creation</span></span><br><span class="line"><span class="comment"> * of the context. Can be overridden in subclasses.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the WebApplicationContext instance</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #FrameworkServlet(WebApplicationContext)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setContextClass</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setContextConfigLocation</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">initWebApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    WebApplicationContext rootContext =</span><br><span class="line">            WebApplicationContextUtils.getWebApplicationContext(getServletContext());</span><br><span class="line">    WebApplicationContext wac = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.webApplicationContext != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// A context instance was injected at construction time -&gt; use it</span></span><br><span class="line">        wac = <span class="keyword">this</span>.webApplicationContext;</span><br><span class="line">        <span class="keyword">if</span> (wac <span class="keyword">instanceof</span> ConfigurableWebApplicationContext) &#123;</span><br><span class="line">            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;</span><br><span class="line">            <span class="keyword">if</span> (!cwac.isActive()) &#123;</span><br><span class="line">                <span class="comment">// The context has not yet been refreshed -&gt; provide services such as</span></span><br><span class="line">                <span class="comment">// setting the parent context, setting the application context id, etc</span></span><br><span class="line">                <span class="keyword">if</span> (cwac.getParent() == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">// The context instance was injected without an explicit parent -&gt; set</span></span><br><span class="line">                    <span class="comment">// the root application context (if any; may be null) as the parent</span></span><br><span class="line">                    cwac.setParent(rootContext);</span><br><span class="line">                &#125;</span><br><span class="line">                configureAndRefreshWebApplicationContext(cwac);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (wac == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// No context instance was injected at construction time -&gt; see if one</span></span><br><span class="line">        <span class="comment">// has been registered in the servlet context. If one exists, it is assumed</span></span><br><span class="line">        <span class="comment">// that the parent context (if any) has already been set and that the</span></span><br><span class="line">        <span class="comment">// user has performed any initialization such as setting the context id</span></span><br><span class="line">        wac = findWebApplicationContext();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (wac == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// No context instance is defined for this servlet -&gt; create a local one</span></span><br><span class="line">        wac = createWebApplicationContext(rootContext);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.refreshEventReceived) &#123;</span><br><span class="line">        <span class="comment">// Either the context is not a ConfigurableApplicationContext with refresh</span></span><br><span class="line">        <span class="comment">// support or the context injected at construction time had already been</span></span><br><span class="line">        <span class="comment">// refreshed -&gt; trigger initial onRefresh manually here.</span></span><br><span class="line">        onRefresh(wac);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.publishContext) &#123;</span><br><span class="line">        <span class="comment">// Publish the context as a servlet context attribute.</span></span><br><span class="line">        String attrName = getServletContextAttributeName();</span><br><span class="line">        getServletContext().setAttribute(attrName, wac);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.debug(<span class="string">"Published WebApplicationContext of servlet '"</span> + getServletName() +</span><br><span class="line">                    <span class="string">"' as ServletContext attribute with name ["</span> + attrName + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> wac;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Template method which can be overridden to add servlet-specific refresh work.</span></span><br><span class="line"><span class="comment"> * Called after successful context refresh.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This implementation is empty.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> context the current WebApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #refresh()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onRefresh</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// For subclasses: do nothing by default.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个方法中，程序先会获取rootContext，rootContext在什么时候会有呢？在你在web.xml中设置了<code>&lt;context-param&gt;</code>标签。什么意思呢？当你有多个Servlet，需要在多个Servlet中间公用一些对象或者数据，就需要设置公共的上下文。公共的上下文也就是在这里被加载到单个Servlet的。</p>
<p>接下来判断对象中的web应用上下文是否已经有了，如果有了，说明是通过别的方式注入进来的，这时候需要给web应用上下文设置父上下文，然后重新初始化web应用上下文。不过这里就不用细究了，一般情况下web应用上下文不会被提前注入。</p>
<p>接下来尝试从容器上下文中获取web应用上下文，一般情况下，也不会从这里创建成功的。</p>
<p>接下来才是<strong>最中心</strong>的，创建 <code>XmlWebApplicationContext</code> 上下文，xml配置文件虽写在web.xml中，其实也就在这里被用到，用于生成上下文。想看源码吗？其实也没什么，就和在Main方法创建上下文一样。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Instantiate the WebApplicationContext for this servlet, either a default</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.web.context.support.XmlWebApplicationContext&#125;</span></span><br><span class="line"><span class="comment"> * or a &#123;<span class="doctag">@link</span> #setContextClass custom context class&#125;, if set.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This implementation expects custom contexts to implement the</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.web.context.ConfigurableWebApplicationContext&#125;</span></span><br><span class="line"><span class="comment"> * interface. Can be overridden in subclasses.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Do not forget to register this servlet instance as application listener on the</span></span><br><span class="line"><span class="comment"> * created context (for triggering its &#123;<span class="doctag">@link</span> #onRefresh callback&#125;, and to call</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.context.ConfigurableApplicationContext#refresh()&#125;</span></span><br><span class="line"><span class="comment"> * before returning the context instance.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> parent the parent ApplicationContext to use, or &#123;<span class="doctag">@code</span> null&#125; if none</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the WebApplicationContext for this servlet</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.context.support.XmlWebApplicationContext</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">createWebApplicationContext</span><span class="params">(ApplicationContext parent)</span> </span>&#123;</span><br><span class="line">    Class&lt;?&gt; contextClass = getContextClass();</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.debug(<span class="string">"Servlet with name '"</span> + getServletName() +</span><br><span class="line">                <span class="string">"' will try to create custom WebApplicationContext context of class '"</span> +</span><br><span class="line">                contextClass.getName() + <span class="string">"'"</span> + <span class="string">", using parent context ["</span> + parent + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!ConfigurableWebApplicationContext<span class="class">.<span class="keyword">class</span>.<span class="title">isAssignableFrom</span>(<span class="title">contextClass</span>)) </span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ApplicationContextException(</span><br><span class="line">                <span class="string">"Fatal initialization error in servlet with name '"</span> + getServletName() +</span><br><span class="line">                <span class="string">"': custom WebApplicationContext class ["</span> + contextClass.getName() +</span><br><span class="line">                <span class="string">"] is not of type ConfigurableWebApplicationContext"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    ConfigurableWebApplicationContext wac =</span><br><span class="line">            (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);</span><br><span class="line"></span><br><span class="line">    wac.setEnvironment(getEnvironment());</span><br><span class="line">    wac.setParent(parent);</span><br><span class="line">    wac.setConfigLocation(getContextConfigLocation());</span><br><span class="line"></span><br><span class="line">    configureAndRefreshWebApplicationContext(wac);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> wac;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">configureAndRefreshWebApplicationContext</span><span class="params">(ConfigurableWebApplicationContext wac)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (ObjectUtils.identityToString(wac).equals(wac.getId())) &#123;</span><br><span class="line">        <span class="comment">// The application context id is still set to its original default value</span></span><br><span class="line">        <span class="comment">// -&gt; assign a more useful id based on available information</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.contextId != <span class="keyword">null</span>) &#123;</span><br><span class="line">            wac.setId(<span class="keyword">this</span>.contextId);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Generate default id...</span></span><br><span class="line">            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +</span><br><span class="line">                    ObjectUtils.getDisplayString(getServletContext().getContextPath()) + <span class="string">"/"</span> + getServletName());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    wac.setServletContext(getServletContext());</span><br><span class="line">    wac.setServletConfig(getServletConfig());</span><br><span class="line">    wac.setNamespace(getNamespace());</span><br><span class="line">    wac.addApplicationListener(<span class="keyword">new</span> SourceFilteringListener(wac, <span class="keyword">new</span> ContextRefreshListener()));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// The wac environment's #initPropertySources will be called in any case when the context</span></span><br><span class="line">    <span class="comment">// is refreshed; do it eagerly here to ensure servlet property sources are in place for</span></span><br><span class="line">    <span class="comment">// use in any post-processing or initialization that occurs below prior to #refresh</span></span><br><span class="line">    ConfigurableEnvironment env = wac.getEnvironment();</span><br><span class="line">    <span class="keyword">if</span> (env <span class="keyword">instanceof</span> ConfigurableWebEnvironment) &#123;</span><br><span class="line">        ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    postProcessWebApplicationContext(wac);</span><br><span class="line">    applyInitializers(wac);</span><br><span class="line">    wac.refresh();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>虽然说一样，其实也不一样，上下文对象是通过反射创建的，然后再注入属性，初始化。为啥要这样？嘿嘿，我想到的原因是可以控制上下文对象初始化的时间/顺序/环绕监听。以后我们也可以这么搞啦。</p>
<p>这里虽然说得很简单，我指的是上下文的创建很简单，但是在SpringMVC框架中设置了很多<strong>自定义标签解析器</strong>，方便使用者开发，这些我们都放到后边用到的时候再讲。</p>
<p>web应用上下文创建完后，<code>FrameworkServlet</code> 还给留了一个onRefresh方法供子类实现。</p>
<h4 id="2-2-2-FrameworkServlet销毁分析"><a href="#2-2-2-FrameworkServlet销毁分析" class="headerlink" title="2.2.2 FrameworkServlet销毁分析"></a>2.2.2 FrameworkServlet销毁分析</h4><p><code>FrameworkServlet</code> 不仅实现了initServletBean方法，还实现了Servlet的destroy方法。该方法会调用web应用上文的close方法，其作用就是完成web应用上下文对对象生命周期的管理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Close the WebApplicationContext of this servlet.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.ConfigurableApplicationContext#close()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    getServletContext().log(<span class="string">"Destroying Spring FrameworkServlet '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">    <span class="comment">// Only call close() on WebApplicationContext if locally managed...</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.webApplicationContext <span class="keyword">instanceof</span> ConfigurableApplicationContext &amp;&amp; !<span class="keyword">this</span>.webApplicationContextInjected) &#123;</span><br><span class="line">        ((ConfigurableApplicationContext) <span class="keyword">this</span>.webApplicationContext).close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-2-3-FrameworkServlet处理请求分析"><a href="#2-2-3-FrameworkServlet处理请求分析" class="headerlink" title="2.2.3 FrameworkServlet处理请求分析"></a>2.2.3 FrameworkServlet处理请求分析</h4><p>针对<code>HttpServlet</code>抽象类将Servlet中的service方法分装成了各个doMethod方法，<code>FrameworkServlet</code> 又将各个方法集中到了processRequest方法中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Process this request, publishing an event regardless of the outcome.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The actual event handling is performed by the abstract</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #doService&#125; template method.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">processRequest</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line">    Throwable failureCause = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();</span><br><span class="line">    LocaleContext localeContext = buildLocaleContext(request);</span><br><span class="line"></span><br><span class="line">    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();</span><br><span class="line">    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);</span><br><span class="line"></span><br><span class="line">    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);</span><br><span class="line">    asyncManager.registerCallableInterceptor(FrameworkServlet<span class="class">.<span class="keyword">class</span>.<span class="title">getName</span>(), <span class="title">new</span> <span class="title">RequestBindingInterceptor</span>())</span>;</span><br><span class="line"></span><br><span class="line">    initContextHolders(request, localeContext, requestAttributes);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        doService(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (ServletException ex) &#123;</span><br><span class="line">        failureCause = ex;</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">        failureCause = ex;</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">        failureCause = ex;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NestedServletException(<span class="string">"Request processing failed"</span>, ex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        resetContextHolders(request, previousLocaleContext, previousAttributes);</span><br><span class="line">        <span class="keyword">if</span> (requestAttributes != <span class="keyword">null</span>) &#123;</span><br><span class="line">            requestAttributes.requestCompleted();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (failureCause != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">this</span>.logger.debug(<span class="string">"Could not complete request"</span>, failureCause);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">                    logger.debug(<span class="string">"Leaving response open for concurrent processing"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">this</span>.logger.debug(<span class="string">"Successfully completed request"</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        publishRequestHandledEvent(request, response, startTime, failureCause);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Subclasses must implement this method to do the work of request handling,</span></span><br><span class="line"><span class="comment"> * receiving a centralized callback for GET, POST, PUT and DELETE.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The contract is essentially the same as that for the commonly overridden</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> doGet&#125; or &#123;<span class="doctag">@code</span> doPost&#125; methods of HttpServlet.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This class intercepts calls to ensure that exception handling and</span></span><br><span class="line"><span class="comment"> * event publication takes place.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception in case of any kind of processing failure</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> javax.servlet.http.HttpServlet#doGet</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> javax.servlet.http.HttpServlet#doPost</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">doService</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>在processRequest方法中，又留下一个doService方法供子类调用。</p>
<h3 id="2-3-DispatcherServlet初始化分析"><a href="#2-3-DispatcherServlet初始化分析" class="headerlink" title="2.3 DispatcherServlet初始化分析"></a>2.3 DispatcherServlet初始化分析</h3><p>在 <code>FrameworkServlet</code> 中，完成了对web应用上下文的创建，并留下了一个onRefresh方法供子类初始化使用。然鹅， <code>FrameworkServlet</code> 就一个子类，它就是<code>DispatcherServlet</code>。留给<code>DispatcherServlet</code> 初始化的入口只有一个那就是onRefresh方法，来看看onRefresh方法吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * This implementation calls &#123;<span class="doctag">@link</span> #initStrategies&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onRefresh</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    initStrategies(context);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the strategy objects that this servlet uses.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;May be overridden in subclasses in order to initialize further strategy objects.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initStrategies</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    initMultipartResolver(context);</span><br><span class="line">    initLocaleResolver(context);</span><br><span class="line">    initThemeResolver(context);</span><br><span class="line">    initHandlerMappings(context);</span><br><span class="line">    initHandlerAdapters(context);</span><br><span class="line">    initHandlerExceptionResolvers(context);</span><br><span class="line">    initRequestToViewNameTranslator(context);</span><br><span class="line">    initViewResolvers(context);</span><br><span class="line">    initFlashMapManager(context);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>onRefresh方法又调用了initStrategies方法，在initStrategies方法里又调用了9个初始化方法。初始化的属性我会做一个简单的介绍，在之后章节会分别再具体介绍。接下来我们分别来看看这几个初始化方法。</p>
<h4 id="2-3-1-initMultipartResolver方法"><a href="#2-3-1-initMultipartResolver方法" class="headerlink" title="2.3.1 initMultipartResolver方法"></a>2.3.1 initMultipartResolver方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the MultipartResolver used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no bean is defined with the given name in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * no multipart handling is provided.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initMultipartResolver</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Using MultipartResolver ["</span> + <span class="keyword">this</span>.multipartResolver + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="comment">// Default is no multipart resolver.</span></span><br><span class="line">        <span class="keyword">this</span>.multipartResolver = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Unable to locate MultipartResolver with name '"</span> + MULTIPART_RESOLVER_BEAN_NAME +</span><br><span class="line">                    <span class="string">"': no multipart request handling provided"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>MULTIPART_RESOLVER_BEAN_NAME</code>值为multipartResolver。</p>
<p>这里我就不卖关子了，这个multipartResolver就是用来解析<code>POST</code>请求中文件部分的。也就是说想设置文件解析器，那这个bean的id必须为multipartResolver。</p>
<h4 id="2-3-2-initLocaleResolver-方法"><a href="#2-3-2-initLocaleResolver-方法" class="headerlink" title="2.3.2 initLocaleResolver 方法"></a>2.3.2 initLocaleResolver 方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the LocaleResolver used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no bean is defined with the given name in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * we default to AcceptHeaderLocaleResolver.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initLocaleResolver</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Using LocaleResolver ["</span> + <span class="keyword">this</span>.localeResolver + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="comment">// We need to use the default.</span></span><br><span class="line">        <span class="keyword">this</span>.localeResolver = getDefaultStrategy(context, LocaleResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Unable to locate LocaleResolver with name '"</span> + LOCALE_RESOLVER_BEAN_NAME +</span><br><span class="line">                    <span class="string">"': using default ["</span> + <span class="keyword">this</span>.localeResolver + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>LOCALE_RESOLVER_BEAN_NAME</code>值为localeResolver。</p>
<p>这个是初始化用户区域解析器，什么是用户区域Locale？我们知道不同国家有不同语言，我们怎么能知道用户所在国家区域？一般来说浏览器请求时会携带一个header头<code>Accept-Language</code>，标识用户可以接受哪些语言。但是还有这种情况，用户希望在这次浏览中查看别的语言版本，前端也允许用户转变语言，那么就不能只从请求头判断了。</p>
<p>所以用户区域解析器不能只有一种，这里SpringMVC允许开发者自定义一个用户区域解析器。如果你想给SpringMVC注入一个自己的用户区域解析器，那么这个bean的id必须为localeResolver。如果不注入的话，默认使用的是从请求头获取用户区域解析器<code>AcceptHeaderLocaleResolver</code>。</p>
<h4 id="2-3-3-initThemeResolver方法"><a href="#2-3-3-initThemeResolver方法" class="headerlink" title="2.3.3 initThemeResolver方法"></a>2.3.3 initThemeResolver方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the ThemeResolver used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no bean is defined with the given name in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * we default to a FixedThemeResolver.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initThemeResolver</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Using ThemeResolver ["</span> + <span class="keyword">this</span>.themeResolver + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="comment">// We need to use the default.</span></span><br><span class="line">        <span class="keyword">this</span>.themeResolver = getDefaultStrategy(context, ThemeResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Unable to locate ThemeResolver with name '"</span> + THEME_RESOLVER_BEAN_NAME +</span><br><span class="line">                    <span class="string">"': using default ["</span> + <span class="keyword">this</span>.themeResolver + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>THEME_RESOLVER_BEAN_NAME</code>值为themeResolver。</p>
<p>这是SpringMVC提供的主题解析器，可以这么来理解，用户区域解析器用来解析用户所在国家，主题解析器则是允许用户选择展示页面的样式。具体怎么用，后面章节会讲到的。如果要自定义主题解析器，那么bean的id名必须为themeResolver。如果没有设置，默认为<code>FiexedThemeResolver</code>，其设置的主题名为theme。</p>
<h4 id="2-3-4-initHandlerMappings方法"><a href="#2-3-4-initHandlerMappings方法" class="headerlink" title="2.3.4 initHandlerMappings方法"></a>2.3.4 <strong>initHandlerMappings</strong>方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the HandlerMappings used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no HandlerMapping beans are defined in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * we default to BeanNameUrlHandlerMapping.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initHandlerMappings</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.handlerMappings = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.detectAllHandlerMappings) &#123;</span><br><span class="line">        <span class="comment">// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.</span></span><br><span class="line">        Map&lt;String, HandlerMapping&gt; matchingBeans =</span><br><span class="line">                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (!matchingBeans.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.handlerMappings = <span class="keyword">new</span> ArrayList&lt;HandlerMapping&gt;(matchingBeans.values());</span><br><span class="line">            <span class="comment">// We keep HandlerMappings in sorted order.</span></span><br><span class="line">            AnnotationAwareOrderComparator.sort(<span class="keyword">this</span>.handlerMappings);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            <span class="keyword">this</span>.handlerMappings = Collections.singletonList(hm);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">            <span class="comment">// Ignore, we'll add a default HandlerMapping later.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Ensure we have at least one HandlerMapping, by registering</span></span><br><span class="line">    <span class="comment">// a default HandlerMapping if no other mappings are found.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.handlerMappings == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.handlerMappings = getDefaultStrategies(context, HandlerMapping<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No HandlerMappings found in servlet '"</span> + getServletName() + <span class="string">"': using default"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>HandlerMapping我们以后会经常看到。</p>
<p>其中，常量<code>HANDLER_MAPPING_BEAN_NAME</code>值为handlerMapping。</p>
<p>detectAllHandlerMappings 属性决定是否检测所有HandlerMapping，可以在web.xml设置，默认为true。web.xml中的设置方式为：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">init-param</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>detectAllHandlerMappings<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>false<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在这个方法中，通过detectAllHandlerMappings判断是否要获取全部HandlerMapping，一般情况下，会获取全部。获取全部HandlerMapping时，会从web应用上下文和父上下文中获取所有HandlerMapping。如果不是获取全部，则会只获取id为handlerMapping的bean。如果一个HandlerMapping都没获取到，则会默认创建<code>BeanNameUrlHandlerMapping</code>和<code>DefaultAnnotationHandlerMapping</code>。</p>
<p>看到这，你会发现怎么老有默认创建的数据，为什么默认是这些呢？别着急，等讲完这些初始化方法，再来看看默认数据。</p>
<h4 id="2-3-5-initHandlerAdapters方法"><a href="#2-3-5-initHandlerAdapters方法" class="headerlink" title="2.3.5 initHandlerAdapters方法"></a>2.3.5 <strong>initHandlerAdapters</strong>方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the HandlerAdapters used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no HandlerAdapter beans are defined in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * we default to SimpleControllerHandlerAdapter.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initHandlerAdapters</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.handlerAdapters = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.detectAllHandlerAdapters) &#123;</span><br><span class="line">        <span class="comment">// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.</span></span><br><span class="line">        Map&lt;String, HandlerAdapter&gt; matchingBeans =</span><br><span class="line">                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (!matchingBeans.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.handlerAdapters = <span class="keyword">new</span> ArrayList&lt;HandlerAdapter&gt;(matchingBeans.values());</span><br><span class="line">            <span class="comment">// We keep HandlerAdapters in sorted order.</span></span><br><span class="line">            AnnotationAwareOrderComparator.sort(<span class="keyword">this</span>.handlerAdapters);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            <span class="keyword">this</span>.handlerAdapters = Collections.singletonList(ha);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">            <span class="comment">// Ignore, we'll add a default HandlerAdapter later.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Ensure we have at least some HandlerAdapters, by registering</span></span><br><span class="line">    <span class="comment">// default HandlerAdapters if no other adapters are found.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.handlerAdapters == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.handlerAdapters = getDefaultStrategies(context, HandlerAdapter<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No HandlerAdapters found in servlet '"</span> + getServletName() + <span class="string">"': using default"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>HandlerAdapter我们以后也会经常看到，它的初始化和HandlerMapping类似。</p>
<p>其中，常量<code>HANDLER_ADAPTER_BEAN_NAME</code>值为handlerAdapter。</p>
<p>detectAllHandlerAdapters 属性决定是否检测所有HandlerAdapter，可以在web.xml设置，默认为true。web.xml中的设置方式为：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">init-param</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>detectAllHandlerAdapters<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>false<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在这个方法中，会判断是否要获取全部HandlerAdapter，一般情况下，是全部获取。获取全部HandlerAdapter时，会从web应用上下文和父上下文中获取所有HandlerAdapter。如果不是获取全部，则会只获取beanId为常量<code>HANDLER_ADAPTER_BEAN_NAME</code>值handlerAdapter的bean。如果一个HandlerAdapter都没获取到，则会默认创建<code>SimpleControllerHandlerAdapter</code>、<code>HttpRequestHandlerAdapter</code>、<code>AnnotationMethodHandlerAdapter</code>。</p>
<h4 id="2-3-6-initHandlerExceptionResolvers方法"><a href="#2-3-6-initHandlerExceptionResolvers方法" class="headerlink" title="2.3.6 initHandlerExceptionResolvers方法"></a>2.3.6 initHandlerExceptionResolvers方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the HandlerExceptionResolver used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no bean is defined with the given name in the BeanFactory for this namespace,</span></span><br><span class="line"><span class="comment"> * we default to no exception resolver.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initHandlerExceptionResolvers</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.handlerExceptionResolvers = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.detectAllHandlerExceptionResolvers) &#123;</span><br><span class="line">        <span class="comment">// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.</span></span><br><span class="line">        Map&lt;String, HandlerExceptionResolver&gt; matchingBeans = BeanFactoryUtils</span><br><span class="line">                .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (!matchingBeans.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.handlerExceptionResolvers = <span class="keyword">new</span> ArrayList&lt;HandlerExceptionResolver&gt;(matchingBeans.values());</span><br><span class="line">            <span class="comment">// We keep HandlerExceptionResolvers in sorted order.</span></span><br><span class="line">            AnnotationAwareOrderComparator.sort(<span class="keyword">this</span>.handlerExceptionResolvers);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            HandlerExceptionResolver her =</span><br><span class="line">                    context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            <span class="keyword">this</span>.handlerExceptionResolvers = Collections.singletonList(her);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">            <span class="comment">// Ignore, no HandlerExceptionResolver is fine too.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Ensure we have at least some HandlerExceptionResolvers, by registering</span></span><br><span class="line">    <span class="comment">// default HandlerExceptionResolvers if no other resolvers are found.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.handlerExceptionResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No HandlerExceptionResolvers found in servlet '"</span> + getServletName() + <span class="string">"': using default"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>HANDLER_EXCEPTION_RESOLVER_BEAN_NAME</code>值为 handlerExceptionResolver。</p>
<p>detectAllHandlerExceptionResolvers 属性决定是否检测所有 HandlerExceptionResolver，可以在web.xml设置，默认为true。web.xml中的设置方式为：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">init-param</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>detectAllHandlerExceptionResolvers<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>false<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在调用用户方法报错时，SpringMVC会把相关信息交给HandlerExceptionResolver解析，默认情况下会获取web应用上下文和父上下文中所有的HandlerExceptionResolver，如果指定只取一个，那么只取id为handlerExceptionResolver的bean。如果一个都没获取到，则默认创建<code>AnnotationMethodHandlerExceptionResolver</code>、<code>ResponseStatusExceptionResolver</code>、<code>DefaultHandlerExceptionResolver</code>。</p>
<h4 id="2-3-7-initRequestToViewNameTranslator方法"><a href="#2-3-7-initRequestToViewNameTranslator方法" class="headerlink" title="2.3.7 initRequestToViewNameTranslator方法"></a>2.3.7 initRequestToViewNameTranslator方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the RequestToViewNameTranslator used by this servlet instance.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no implementation is configured then we default to DefaultRequestToViewNameTranslator.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initRequestToViewNameTranslator</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.viewNameTranslator =</span><br><span class="line">                context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Using RequestToViewNameTranslator ["</span> + <span class="keyword">this</span>.viewNameTranslator + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="comment">// We need to use the default.</span></span><br><span class="line">        <span class="keyword">this</span>.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Unable to locate RequestToViewNameTranslator with name '"</span> +</span><br><span class="line">                    REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME + <span class="string">"': using default ["</span> + <span class="keyword">this</span>.viewNameTranslator +</span><br><span class="line">                    <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME</code>值为 viewNameTranslator。</p>
<p>当前置控制器DispatcherServlet调用完用户方法后，用户方法既没有返回可用的视图名，也没有给response写数据，则需要通过 RequestToViewNameTranslator 生成一个默认的视图名。如果想自定义视图翻译器，那么bean的id必须为viewNameTranslator。如果没有获取到bean，则默认创建<code>DefaultRequestToViewNameTranslator</code>，默认视图翻译器根据URI来生成视图名。</p>
<h4 id="2-3-8-initViewResolvers方法"><a href="#2-3-8-initViewResolvers方法" class="headerlink" title="2.3.8 initViewResolvers方法"></a>2.3.8 <strong>initViewResolvers</strong>方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the ViewResolvers used by this class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no ViewResolver beans are defined in the BeanFactory for this</span></span><br><span class="line"><span class="comment"> * namespace, we default to InternalResourceViewResolver.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initViewResolvers</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.viewResolvers = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.detectAllViewResolvers) &#123;</span><br><span class="line">        <span class="comment">// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.</span></span><br><span class="line">        Map&lt;String, ViewResolver&gt; matchingBeans =</span><br><span class="line">                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (!matchingBeans.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">this</span>.viewResolvers = <span class="keyword">new</span> ArrayList&lt;ViewResolver&gt;(matchingBeans.values());</span><br><span class="line">            <span class="comment">// We keep ViewResolvers in sorted order.</span></span><br><span class="line">            AnnotationAwareOrderComparator.sort(<span class="keyword">this</span>.viewResolvers);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            <span class="keyword">this</span>.viewResolvers = Collections.singletonList(vr);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">            <span class="comment">// Ignore, we'll add a default ViewResolver later.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Ensure we have at least one ViewResolver, by registering</span></span><br><span class="line">    <span class="comment">// a default ViewResolver if no other resolvers are found.</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.viewResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">this</span>.viewResolvers = getDefaultStrategies(context, ViewResolver<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"No ViewResolvers found in servlet '"</span> + getServletName() + <span class="string">"': using default"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>ViewResolver我们以后也会经常看到。</p>
<p>其中，常量<code>VIEW_RESOLVER_BEAN_NAME</code>值为viewResolver。</p>
<p>默认情况下，初始化方法会获取wen应用上下文和父上下文中所有的ViewResolver。如果指定只取一个，那么将会取id名为常量viewResolver的bean。如果都没有获取到，则会默认创建<code>InternalResourceViewResolver</code>。</p>
<h4 id="2-3-9-initFlashMapManager方法"><a href="#2-3-9-initFlashMapManager方法" class="headerlink" title="2.3.9 initFlashMapManager方法"></a>2.3.9 initFlashMapManager方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the &#123;<span class="doctag">@link</span> FlashMapManager&#125; used by this servlet instance.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no implementation is configured then we default to</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> org.springframework.web.servlet.support.DefaultFlashMapManager&#125;.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initFlashMapManager</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Using FlashMapManager ["</span> + <span class="keyword">this</span>.flashMapManager + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">        <span class="comment">// We need to use the default.</span></span><br><span class="line">        <span class="keyword">this</span>.flashMapManager = getDefaultStrategy(context, FlashMapManager<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Unable to locate FlashMapManager with name '"</span> +</span><br><span class="line">                    FLASH_MAP_MANAGER_BEAN_NAME + <span class="string">"': using default ["</span> + <span class="keyword">this</span>.flashMapManager + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，常量<code>FLASH_MAP_MANAGER_BEAN_NAME</code>值为flashMapManager。</p>
<p>当开发者使用redirect重定向用户到另一个页面，当前的数据将会丢失，使用FlashMap可以解决这个问题，FlashMapManager就是管理FlashMap的。如果想自定义FlashMapManager，那么bean的id必须为flashMapManager。如果没有获取到bean，则默认创建<code>SessionFlashMapManager</code>。</p>
<h4 id="2-3-10-DispatcherServlet初始化方法中的默认值"><a href="#2-3-10-DispatcherServlet初始化方法中的默认值" class="headerlink" title="2.3.10 DispatcherServlet初始化方法中的默认值"></a>2.3.10 DispatcherServlet初始化方法中的默认值</h4><p>在前9个方法中，我们发现在上下文中没有得到相应的实现类对象时，会默认指定一些默认值。这是怎么回事呢？</p>
<p>先来看看这个静态方法块。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Name of the class path resource (relative to the DispatcherServlet class)</span><br><span class="line"> * that defines DispatcherServlet&apos;s default strategy names.</span><br><span class="line"> */</span><br><span class="line">private static final String DEFAULT_STRATEGIES_PATH = &quot;DispatcherServlet.properties&quot;;</span><br><span class="line"></span><br><span class="line">private static final Properties defaultStrategies;</span><br><span class="line"></span><br><span class="line">static &#123;</span><br><span class="line">    // Load default strategy implementations from properties file.</span><br><span class="line">    // This is currently strictly internal and not meant to be customized</span><br><span class="line">    // by application developers.</span><br><span class="line">    try &#123;</span><br><span class="line">        ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);</span><br><span class="line">        defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);</span><br><span class="line">    &#125;</span><br><span class="line">    catch (IOException ex) &#123;</span><br><span class="line">        throw new IllegalStateException(&quot;Could not load &apos;DispatcherServlet.properties&apos;: &quot; + ex.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这块代码的含义是读取<code>DispatcherServlet</code>类所在包下文件名为DispatcherServlet.properties的文件</p>
<p>我们再看看DispatcherServlet.properties文件内容</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"># Default implementation classes for DispatcherServlet&apos;s strategy interfaces.</span><br><span class="line"># Used as fallback when no matching beans are found in the DispatcherServlet context.</span><br><span class="line"># Not meant to be customized by application developers.</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\</span><br><span class="line">    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\</span><br><span class="line">    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\</span><br><span class="line">    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\</span><br><span class="line">    org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\</span><br><span class="line">    org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver</span><br><span class="line"></span><br><span class="line">org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager</span><br></pre></td></tr></table></figure>

<p>看到了吗？所有的默认值均来自这里，这就简单了，我们再看看哪里使用到了<code>defaultStrategies</code>属性。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the default strategy object for the given strategy interface.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation delegates to &#123;<span class="doctag">@link</span> #getDefaultStrategies&#125;,</span></span><br><span class="line"><span class="comment"> * expecting a single object in the list.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> context the current WebApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> strategyInterface the strategy interface</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the corresponding strategy object</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getDefaultStrategies</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">getDefaultStrategy</span><span class="params">(ApplicationContext context, Class&lt;T&gt; strategyInterface)</span> </span>&#123;</span><br><span class="line">    List&lt;T&gt; strategies = getDefaultStrategies(context, strategyInterface);</span><br><span class="line">    <span class="keyword">if</span> (strategies.size() != <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(</span><br><span class="line">                <span class="string">"DispatcherServlet needs exactly 1 strategy for interface ["</span> + strategyInterface.getName() + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> strategies.get(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Create a List of default strategy objects for the given strategy interface.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation uses the "DispatcherServlet.properties" file (in the same</span></span><br><span class="line"><span class="comment"> * package as the DispatcherServlet class) to determine the class names. It instantiates</span></span><br><span class="line"><span class="comment"> * the strategy objects through the context's BeanFactory.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> context the current WebApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> strategyInterface the strategy interface</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the List of corresponding strategy objects</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">List&lt;T&gt; <span class="title">getDefaultStrategies</span><span class="params">(ApplicationContext context, Class&lt;T&gt; strategyInterface)</span> </span>&#123;</span><br><span class="line">    String key = strategyInterface.getName();</span><br><span class="line">    String value = defaultStrategies.getProperty(key);</span><br><span class="line">    <span class="keyword">if</span> (value != <span class="keyword">null</span>) &#123;</span><br><span class="line">        String[] classNames = StringUtils.commaDelimitedListToStringArray(value);</span><br><span class="line">        List&lt;T&gt; strategies = <span class="keyword">new</span> ArrayList&lt;T&gt;(classNames.length);</span><br><span class="line">        <span class="keyword">for</span> (String className : classNames) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Class&lt;?&gt; clazz = ClassUtils.forName(className, DispatcherServlet<span class="class">.<span class="keyword">class</span>.<span class="title">getClassLoader</span>())</span>;</span><br><span class="line">                Object strategy = createDefaultStrategy(context, clazz);</span><br><span class="line">                strategies.add((T) strategy);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (ClassNotFoundException ex) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(</span><br><span class="line">                        <span class="string">"Could not find DispatcherServlet's default strategy class ["</span> + className +</span><br><span class="line">                                <span class="string">"] for interface ["</span> + key + <span class="string">"]"</span>, ex);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (LinkageError err) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(</span><br><span class="line">                        <span class="string">"Error loading DispatcherServlet's default strategy class ["</span> + className +</span><br><span class="line">                                <span class="string">"] for interface ["</span> + key + <span class="string">"]: problem with class file or dependent class"</span>, err);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> strategies;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> LinkedList&lt;T&gt;();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Create a default strategy.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation uses</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean&#125;.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> context the current WebApplicationContext</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> clazz the strategy implementation class to instantiate</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the fully configured strategy instance</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">createDefaultStrategy</span><span class="params">(ApplicationContext context, Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> context.getAutowireCapableBeanFactory().createBean(clazz);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这块代码略读就行，我们就知道默认数据从哪来就行。</p>
<h4 id="2-3-11-小结"><a href="#2-3-11-小结" class="headerlink" title="2.3.11 小结"></a>2.3.11 小结</h4><p><code>DispatcherServlet</code>的初始化部分总算是理清楚了。以上几节，我们了解了SpringMVC通过继承<code>HttpServlet</code>从而生成了一个前置控制器，通过层层转包Servlet的init方法，在<code>FramworkServlet</code>中执行initServletBean方法生成了web应用上下文，在<code>DispatcherServlet</code>中执行onRefresh方法初始化了<code>DispatcherServlet</code>中的相关属性。</p>
<h3 id="2-4-DispatcherServlet处理请求分析"><a href="#2-4-DispatcherServlet处理请求分析" class="headerlink" title="2.4 DispatcherServlet处理请求分析"></a>2.4 DispatcherServlet处理请求分析</h3><p>由于<code>FramworkServlet</code>将处理请求集中到了doService方法中，<code>DispatcherServlet</code>处理请求分析也将从doServie方法实现中展开。</p>
<h4 id="2-4-1-doService方法"><a href="#2-4-1-doService方法" class="headerlink" title="2.4.1 doService方法"></a>2.4.1 doService方法</h4><p>doService方法比较简单，向request设置一些属性信息，然后调用doDispatch方法进行请求处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Exposes the DispatcherServlet-specific request attributes and delegates to &#123;<span class="doctag">@link</span> #doDispatch&#125;</span></span><br><span class="line"><span class="comment"> * for the actual dispatching.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doService</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? <span class="string">" resumed"</span> : <span class="string">""</span>;</span><br><span class="line">        logger.debug(<span class="string">"DispatcherServlet with name '"</span> + getServletName() + <span class="string">"'"</span> + resumed +</span><br><span class="line">                <span class="string">" processing "</span> + request.getMethod() + <span class="string">" request for ["</span> + getRequestUri(request) + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Keep a snapshot of the request attributes in case of an include,</span></span><br><span class="line">    <span class="comment">// to be able to restore the original attributes after the include.</span></span><br><span class="line">    Map&lt;String, Object&gt; attributesSnapshot = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (WebUtils.isIncludeRequest(request)) &#123;</span><br><span class="line">        attributesSnapshot = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        Enumeration&lt;?&gt; attrNames = request.getAttributeNames();</span><br><span class="line">        <span class="keyword">while</span> (attrNames.hasMoreElements()) &#123;</span><br><span class="line">            String attrName = (String) attrNames.nextElement();</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.cleanupAfterInclude || attrName.startsWith(<span class="string">"org.springframework.web.servlet"</span>)) &#123;</span><br><span class="line">                attributesSnapshot.put(attrName, request.getAttribute(attrName));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Make framework objects available to handlers and view objects.</span></span><br><span class="line">    request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());</span><br><span class="line">    request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, <span class="keyword">this</span>.localeResolver);</span><br><span class="line">    request.setAttribute(THEME_RESOLVER_ATTRIBUTE, <span class="keyword">this</span>.themeResolver);</span><br><span class="line">    request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());</span><br><span class="line"></span><br><span class="line">    FlashMap inputFlashMap = <span class="keyword">this</span>.flashMapManager.retrieveAndUpdate(request, response);</span><br><span class="line">    <span class="keyword">if</span> (inputFlashMap != <span class="keyword">null</span>) &#123;</span><br><span class="line">        request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));</span><br><span class="line">    &#125;</span><br><span class="line">    request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, <span class="keyword">new</span> FlashMap());</span><br><span class="line">    request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, <span class="keyword">this</span>.flashMapManager);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        doDispatch(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) &#123;</span><br><span class="line">            <span class="comment">// Restore the original attribute snapshot, in case of an include.</span></span><br><span class="line">            <span class="keyword">if</span> (attributesSnapshot != <span class="keyword">null</span>) &#123;</span><br><span class="line">                restoreAttributesAfterInclude(request, attributesSnapshot);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们看到，向request的属性中注入了web应用上下文，用户区域解析器，主题解析器和flashMapManager，这些都是在初始化时生成的。</p>
<h4 id="2-4-2-doDispatch方法"><a href="#2-4-2-doDispatch方法" class="headerlink" title="2.4.2 doDispatch方法"></a>2.4.2 doDispatch方法</h4><p>doDispatch方法在较高程度上抽象MVC，在这个方法里，你将看到很多接口。请打起精神，仔细体会。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Process the actual dispatching to the handler.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The handler will be obtained by applying the servlet's HandlerMappings in order.</span></span><br><span class="line"><span class="comment"> * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters</span></span><br><span class="line"><span class="comment"> * to find the first that supports the handler class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers</span></span><br><span class="line"><span class="comment"> * themselves to decide which methods are acceptable.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception in case of any kind of processing failure</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doDispatch</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HttpServletRequest processedRequest = request;</span><br><span class="line">    HandlerExecutionChain mappedHandler = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">boolean</span> multipartRequestParsed = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        ModelAndView mv = <span class="keyword">null</span>;</span><br><span class="line">        Exception dispatchException = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            processedRequest = checkMultipart(request);</span><br><span class="line">            multipartRequestParsed = (processedRequest != request);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Determine handler for the current request.</span></span><br><span class="line">            mappedHandler = getHandler(processedRequest);</span><br><span class="line">            <span class="keyword">if</span> (mappedHandler == <span class="keyword">null</span> || mappedHandler.getHandler() == <span class="keyword">null</span>) &#123;</span><br><span class="line">                noHandlerFound(processedRequest, response);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Determine handler adapter for the current request.</span></span><br><span class="line">            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Process last-modified header, if supported by the handler.</span></span><br><span class="line">            String method = request.getMethod();</span><br><span class="line">            <span class="keyword">boolean</span> isGet = <span class="string">"GET"</span>.equals(method);</span><br><span class="line">            <span class="keyword">if</span> (isGet || <span class="string">"HEAD"</span>.equals(method)) &#123;</span><br><span class="line">                <span class="keyword">long</span> lastModified = ha.getLastModified(request, mappedHandler.getHandler());</span><br><span class="line">                <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                    logger.debug(<span class="string">"Last-Modified value for ["</span> + getRequestUri(request) + <span class="string">"] is: "</span> + lastModified);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">new</span> ServletWebRequest(request, response).checkNotModified(lastModified) &amp;&amp; isGet) &#123;</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (!mappedHandler.applyPreHandle(processedRequest, response)) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Actually invoke the handler.</span></span><br><span class="line">            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            applyDefaultViewName(processedRequest, mv);</span><br><span class="line">            mappedHandler.applyPostHandle(processedRequest, response, mv);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">            dispatchException = ex;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Throwable err) &#123;</span><br><span class="line">            <span class="comment">// As of 4.3, we're processing Errors thrown from handler methods as well,</span></span><br><span class="line">            <span class="comment">// making them available for @ExceptionHandler methods and other scenarios.</span></span><br><span class="line">            dispatchException = <span class="keyword">new</span> NestedServletException(<span class="string">"Handler dispatch failed"</span>, err);</span><br><span class="line">        &#125;</span><br><span class="line">        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Throwable err) &#123;</span><br><span class="line">        triggerAfterCompletion(processedRequest, response, mappedHandler,</span><br><span class="line">                <span class="keyword">new</span> NestedServletException(<span class="string">"Handler processing failed"</span>, err));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">            <span class="comment">// Instead of postHandle and afterCompletion</span></span><br><span class="line">            <span class="keyword">if</span> (mappedHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Clean up any resources used by a multipart request.</span></span><br><span class="line">            <span class="keyword">if</span> (multipartRequestParsed) &#123;</span><br><span class="line">                cleanupMultipart(processedRequest);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第17行代码中，尝试从request中获取一个<code>WebAsyncManager</code>，Async特性是出现在Servlet3.0规范中，允许Servlet容器将socket的所有权交给用户业务线程处理，从而释放出Servlet容器的线程，供更多连接请求使用。目前我们先不对这个特性做过多描述，如果想了解更多内容，可以参考我的其他文章。</p>
<p>在第24行代码中，检测是否包含<code>POST</code>请求的文件上传。checkMultipart 方法会先判断 multipartResolver 属性是否为null。如果不为null，就调用 multipartResolver 接口的 isMultipart 方法判断是不是文件上传。如果是文件上传，并且入参request没有解析成文件上传request，且request的属性中没有文件上传异常，就调用 multipartResolver 接口的 resolveMultipart 方法返回文件上传request。否则返回原request。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Convert the request into a multipart request, and make multipart resolver available.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;If no multipart resolver is set, simply use the existing request.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the processed request (multipart wrapper if necessary)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> MultipartResolver#resolveMultipart</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HttpServletRequest <span class="title">checkMultipart</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.multipartResolver != <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.multipartResolver.isMultipart(request)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (WebUtils.getNativeRequest(request, MultipartHttpServletRequest<span class="class">.<span class="keyword">class</span>) !</span>= <span class="keyword">null</span>) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Request is already a MultipartHttpServletRequest - if not in a forward, "</span> +</span><br><span class="line">                    <span class="string">"this typically results from an additional MultipartFilter in web.xml"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) <span class="keyword">instanceof</span> MultipartException) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Multipart resolution failed for current request before - "</span> +</span><br><span class="line">                    <span class="string">"skipping re-resolution for undisturbed error rendering"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.multipartResolver.resolveMultipart(request);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// If not returned before: return original request.</span></span><br><span class="line">    <span class="keyword">return</span> request;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第28行代码中，调用了getHandler方法挑选出一个合适的HandlerExecutionChain（也被成为执行链）。在 2.3.4 节初始化 HandlerMapping 中，我们会得到一组 HandlerMapping 实现类对象。在getHandler方法中，就是循环这些HandlerMapping，如果有一个HandlerMapping调用方法得到了非空的HandlerExecutionChain对象，就说明这个HandlerMapping可以映射到一个执行链。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the HandlerExecutionChain for this request.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Tries all handler mappings in order.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the HandlerExecutionChain, or &#123;<span class="doctag">@code</span> null&#125; if no handler could be found</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerExecutionChain <span class="title">getHandler</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (HandlerMapping hm : <span class="keyword">this</span>.handlerMappings) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(</span><br><span class="line">                    <span class="string">"Testing handler map ["</span> + hm + <span class="string">"] in DispatcherServlet with name '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        HandlerExecutionChain handler = hm.getHandler(request);</span><br><span class="line">        <span class="keyword">if</span> (handler != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> handler;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第29行到32行代码中，会判断有没有得到一个执行链。如果没有得到执行链，说明开发者没有编写URI对应的方法或文件。这时候 noHandlerFound 方法有两种选择，如果属性 throwExceptionIfNoHandlerFound 为true，抛出异常，否则向response发送一个404状态码然后结束。throwExceptionIfNoHandlerFound 属性可以在web.xml设置，默认为 false。web.xml中的设置方式为：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">init-param</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>throwExceptionIfNoHandlerFound<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span>  </span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>true<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span>  </span><br><span class="line"><span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>noHandlerFound方法代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * No handler found -&gt; set appropriate HTTP response status.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if preparing the response failed</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">noHandlerFound</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (pageNotFoundLogger.isWarnEnabled()) &#123;</span><br><span class="line">        pageNotFoundLogger.warn(<span class="string">"No mapping found for HTTP request with URI ["</span> + getRequestUri(request) +</span><br><span class="line">                <span class="string">"] in DispatcherServlet with name '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.throwExceptionIfNoHandlerFound) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NoHandlerFoundException(request.getMethod(), getRequestUri(request),</span><br><span class="line">                <span class="keyword">new</span> ServletServerHttpRequest(request).getHeaders());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        response.sendError(HttpServletResponse.SC_NOT_FOUND);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第35行代码中，调用 getHandlerAdapter 方法取得一个 HandlerAdapter ，HandlerAdapter 是由 2.3.5节中initHandlerAdapter初始化生成的，如果所有 HandlerAdapter 都不支持该handler，就会抛出异常。由于执行链中的 handler 类型为Object，<code>DispatcherServlet</code> 并不能执行handler，所以需要一个 HandlerAdapter 适配器来执行它。怎么判断一个 HandlerAdapter 是否能够执行 handler呢？HandlerAdapter 接口有一个 supports 方法是用来判断是否支持的。getHandlerAdapter 方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Return the HandlerAdapter for this handler object.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the handler object to find an adapter for</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerAdapter <span class="title">getHandlerAdapter</span><span class="params">(Object handler)</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (HandlerAdapter ha : <span class="keyword">this</span>.handlerAdapters) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(<span class="string">"Testing handler adapter ["</span> + ha + <span class="string">"]"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (ha.supports(handler)) &#123;</span><br><span class="line">            <span class="keyword">return</span> ha;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"No adapter for handler ["</span> + handler +</span><br><span class="line">            <span class="string">"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第50行到第52行代码中，会先调用执行链的applyPreHandle方法，看名字就知道是申请预处理。如果预处理返回了false结果，就直接返回，实际情况中预处理主要是判断是否已登录、记录开始日志、注入相应上下文等功能。</p>
<p>在第55行代码中，由 HandlerAdapter 来执行之前从 HandlerMapping 中获得的handler ，返回的是 ModelAndView。</p>
<p>在第57行到59行代码中，还是Servlet3.0规范特性，如果是异步执行的，就直接返回不做任何处理，这里也不做细究。</p>
<p>在第61行代码中，尝试注入默认视图名。什么意思呢？得到的 ModelAndView 可能并没有指定view，这时候需要设置一个默认的view。还记得在 2.3.7 初始化 viewNameTranslator 视图翻译器吧，就是在这里工作的。方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Do we need view name translation?</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">applyDefaultViewName</span><span class="params">(HttpServletRequest request, ModelAndView mv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (mv != <span class="keyword">null</span> &amp;&amp; !mv.hasView()) &#123;</span><br><span class="line">        mv.setViewName(getDefaultViewName(request));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Translate the supplied request into a default view name.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP servlet request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the view name (or &#123;<span class="doctag">@code</span> null&#125; if no default found)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if view name translation failed</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> String <span class="title">getDefaultViewName</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.viewNameTranslator.getViewName(request);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第62行代码中，调用执行链的applyPostHandle方法，看名字就知道是申请后处理。实际情况中后处理主要是修改 ModelAndView 。</p>
<p>在第72行代码中，会对整个处理结果做一个整理。因为在整个处理过程中，有很多地方会抛出异常并被设置到 dispatchException 参数中，也有可能得到正常结果。在 processDispatchResult 方法中，会先判断是否有异常产生，如果有异常产生，会给 HandlerExceptionResolver 一个机会去捕捉异常，HandlerExceptionResolver 是在 2.3.6节初始化的，如果有一个 HandlerExceptionResolver 可以产生正常的 ModelAndView，就会继续正常执行。</p>
<p>如果产生了 ModelAndView，就会调用render方法真正的向response写入经过view和model渲染的字节数据。如果不是异步执行的，还会触发执行链的 triggerAfterCompletion 完成后触发方法。具体的方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Handle the result of handler selection and handler invocation, which is</span></span><br><span class="line"><span class="comment"> * either a ModelAndView or an Exception to be resolved to a ModelAndView.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">processDispatchResult</span><span class="params">(HttpServletRequest request, HttpServletResponse response,</span></span></span><br><span class="line"><span class="function"><span class="params">        HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">boolean</span> errorView = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (exception != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (exception <span class="keyword">instanceof</span> ModelAndViewDefiningException) &#123;</span><br><span class="line">            logger.debug(<span class="string">"ModelAndViewDefiningException encountered"</span>, exception);</span><br><span class="line">            mv = ((ModelAndViewDefiningException) exception).getModelAndView();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            Object handler = (mappedHandler != <span class="keyword">null</span> ? mappedHandler.getHandler() : <span class="keyword">null</span>);</span><br><span class="line">            mv = processHandlerException(request, response, handler, exception);</span><br><span class="line">            errorView = (mv != <span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Did the handler return a view to render?</span></span><br><span class="line">    <span class="keyword">if</span> (mv != <span class="keyword">null</span> &amp;&amp; !mv.wasCleared()) &#123;</span><br><span class="line">        render(mv, request, response);</span><br><span class="line">        <span class="keyword">if</span> (errorView) &#123;</span><br><span class="line">            WebUtils.clearErrorRequestAttributes(request);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Null ModelAndView returned to DispatcherServlet with name '"</span> + getServletName() +</span><br><span class="line">                    <span class="string">"': assuming HandlerAdapter completed request handling"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) &#123;</span><br><span class="line">        <span class="comment">// Concurrent handling started during a forward</span></span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mappedHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">        mappedHandler.triggerAfterCompletion(request, response, <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Determine an error ModelAndView via the registered HandlerExceptionResolvers.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the executed handler, or &#123;<span class="doctag">@code</span> null&#125; if none chosen at the time of the exception</span></span><br><span class="line"><span class="comment"> * (for example, if multipart resolution failed)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> ex the exception that got thrown during handler execution</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> a corresponding ModelAndView to forward to</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if no error ModelAndView found</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> ModelAndView <span class="title">processHandlerException</span><span class="params">(HttpServletRequest request, HttpServletResponse response,</span></span></span><br><span class="line"><span class="function"><span class="params">        Object handler, Exception ex)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Check registered HandlerExceptionResolvers...</span></span><br><span class="line">    ModelAndView exMv = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">for</span> (HandlerExceptionResolver handlerExceptionResolver : <span class="keyword">this</span>.handlerExceptionResolvers) &#123;</span><br><span class="line">        exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);</span><br><span class="line">        <span class="keyword">if</span> (exMv != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (exMv != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (exMv.isEmpty()) &#123;</span><br><span class="line">            request.setAttribute(EXCEPTION_ATTRIBUTE, ex);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// We might still need view name translation for a plain error model...</span></span><br><span class="line">        <span class="keyword">if</span> (!exMv.hasView()) &#123;</span><br><span class="line">            exMv.setViewName(getDefaultViewName(request));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Handler execution resulted in exception - forwarding to resolved error view: "</span> + exMv, ex);</span><br><span class="line">        &#125;</span><br><span class="line">        WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());</span><br><span class="line">        <span class="keyword">return</span> exMv;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">throw</span> ex;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果在 processDispatchResult 处理异常或正常结果时还抛出了异常，就会被第74到第80行代码cache住，调用执行链的 triggerAfterCompletion 完成后触发方法。</p>
<p>最后第81行到第93行，会判断是否需要调用执行链的异步执行开始触发器和是否需要清除文件上传的中间临时磁盘数据。</p>
<h4 id="2-4-3-render方法"><a href="#2-4-3-render方法" class="headerlink" title="2.4.3 render方法"></a>2.4.3 render方法</h4><p>render方法单独提出来，因为前置处理器作为MVC的C已经调用了在MVC中属于M的可执行链。如果返回了模型数据 ModelAndView，就需要调用MVC中的V进行视图渲染了。</p>
<p>render方法相比于 doDispatch 方法还是很简单的。首先它会通过 2.3.2节初始化的用户区域解析器解析到区域信息，然后调用 2.3.8节初始化的 viewResolver 获取View实现类对象。得到了View实现类对象后，直接调用View接口的render方法，整合模型数据，向response写入字节数据。以下是具体代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Render the given ModelAndView.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This is the last stage in handling a request. It may involve resolving the view by name.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> mv the ModelAndView to render</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP servlet request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> response current HTTP servlet response</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ServletException if view is missing or cannot be resolved</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if there's a problem rendering the view</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">render</span><span class="params">(ModelAndView mv, HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Determine locale for request and apply it to the response.</span></span><br><span class="line">    Locale locale = <span class="keyword">this</span>.localeResolver.resolveLocale(request);</span><br><span class="line">    response.setLocale(locale);</span><br><span class="line"></span><br><span class="line">    View view;</span><br><span class="line">    <span class="keyword">if</span> (mv.isReference()) &#123;</span><br><span class="line">        <span class="comment">// We need to resolve the view name.</span></span><br><span class="line">        view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);</span><br><span class="line">        <span class="keyword">if</span> (view == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"Could not resolve view with name '"</span> + mv.getViewName() +</span><br><span class="line">                    <span class="string">"' in servlet with name '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// No need to lookup: the ModelAndView object contains the actual View object.</span></span><br><span class="line">        view = mv.getView();</span><br><span class="line">        <span class="keyword">if</span> (view == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">"ModelAndView ["</span> + mv + <span class="string">"] neither contains a view name nor a "</span> +</span><br><span class="line">                    <span class="string">"View object in servlet with name '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Delegate to the View object for rendering.</span></span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Rendering view ["</span> + view + <span class="string">"] in DispatcherServlet with name '"</span> + getServletName() + <span class="string">"'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (mv.getStatus() != <span class="keyword">null</span>) &#123;</span><br><span class="line">            response.setStatus(mv.getStatus().value());</span><br><span class="line">        &#125;</span><br><span class="line">        view.render(mv.getModelInternal(), request, response);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Error rendering view ["</span> + view + <span class="string">"] in DispatcherServlet with name '"</span> +</span><br><span class="line">                    getServletName() + <span class="string">"'"</span>, ex);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> ex;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Resolve the given view name into a View object (to be rendered).</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementations asks all ViewResolvers of this dispatcher.</span></span><br><span class="line"><span class="comment"> * Can be overridden for custom resolution strategies, potentially based on</span></span><br><span class="line"><span class="comment"> * specific model attributes or request parameters.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> viewName the name of the view to resolve</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> model the model to be passed to the view</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> locale the current locale</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP servlet request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the View object, or &#123;<span class="doctag">@code</span> null&#125; if none found</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if the view cannot be resolved</span></span><br><span class="line"><span class="comment"> * (typically in case of problems creating an actual View object)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> ViewResolver#resolveViewName</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> View <span class="title">resolveViewName</span><span class="params">(String viewName, Map&lt;String, Object&gt; model, Locale locale,</span></span></span><br><span class="line"><span class="function"><span class="params">        HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (ViewResolver viewResolver : <span class="keyword">this</span>.viewResolvers) &#123;</span><br><span class="line">        View view = viewResolver.resolveViewName(viewName, locale);</span><br><span class="line">        <span class="keyword">if</span> (view != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> view;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-4-4-小结"><a href="#2-4-4-小结" class="headerlink" title="2.4.4 小结"></a>2.4.4 小结</h4><p>处理请求比起初始化看来真是复杂了很多。不过只要抓住MVC模式思想，还是比较容易理清楚的。</p>
<ol>
<li>首先得到requesr后，需要给request注入一些属性，方便处理，例如web应用上下文、用户区域解析器、主题解析器，flashMapManager等等。</li>
<li>其次再判断是否是POST文件上传请求，如果是就解析该请求。</li>
<li>之后就通过 HandlerMapping 获取执行链，如果没得到执行链，要么抛异常，要么发送一个404响应然后结束。</li>
<li>得到了执行链，需要获取可以执行执行链的 HandlerAdapter ，如果没获取到就抛异常。</li>
<li>得到了 HandlerAdapter 后，先调用执行链的预处理器，如果返回false，就结束此次请求。</li>
<li>调用 HandlerAdapter 执行执行链。</li>
<li>之后就处理默认视图名，调用执行链的后置处理器。</li>
<li>C和M之间的事情处理完后，该考虑V了</li>
<li>此时，如果之前产生了异常，给 HandlerExceptionResolver 一个机会生成一个正常的 ModelAndView。如果没有生成，只好再抛异常。</li>
<li>此时还没抛异常，说明有正常的 ModelAndView。</li>
<li>获取用户区域信息，通过 ViewResolver 得到View接口，调用View接口的render方法渲染页面。</li>
<li>调用执行链的完成后触发方法。</li>
<li>处理V的事情如果抛了异常，还会调用执行链的完成后触发方法。</li>
<li>最终处理一下异步的触发器事件，销毁一下文件上传产生的临时磁盘文件。</li>
</ol>
<p>在第2章，我们简单过了<code>DispatcherServlet</code>和他的父类。可以看出，我只是囫囵吞枣般的解析了<code>DispatcherServlet</code>和他父类的初始化、销毁和请求处理。对，我就是刻意这么做的，就是不让大家陷入到SpringMVC的复杂嵌套逻辑中。在接下来的这几章咱们来分别深入了解一下在<code>DispatcherServlet</code>中出现的各种接口。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-1/" title="SpringMVC 解毒1">http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/06/how-to-use-cache-in-redis/" rel="next" title="如何利用redis实现缓存">
                <i class="fa fa-chevron-left"></i> 如何利用redis实现缓存
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-2/" rel="prev" title="SpringMVC 解毒2">
                SpringMVC 解毒2 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0-前言"><span class="nav-number">1.</span> <span class="nav-text">0 前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-MVC-简介"><span class="nav-number">2.</span> <span class="nav-text">1 MVC 简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-DispatcherServlet"><span class="nav-number">3.</span> <span class="nav-text">2 DispatcherServlet</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-HttpServletBean分析"><span class="nav-number">3.1.</span> <span class="nav-text">2.1 HttpServletBean分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-FrameworkServlet分析"><span class="nav-number">3.2.</span> <span class="nav-text">2.2 FrameworkServlet分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-FrameworkServlet初始化分析"><span class="nav-number">3.2.1.</span> <span class="nav-text">2.2.1 FrameworkServlet初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-2-FrameworkServlet销毁分析"><span class="nav-number">3.2.2.</span> <span class="nav-text">2.2.2 FrameworkServlet销毁分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-3-FrameworkServlet处理请求分析"><span class="nav-number">3.2.3.</span> <span class="nav-text">2.2.3 FrameworkServlet处理请求分析</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-DispatcherServlet初始化分析"><span class="nav-number">3.3.</span> <span class="nav-text">2.3 DispatcherServlet初始化分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-1-initMultipartResolver方法"><span class="nav-number">3.3.1.</span> <span class="nav-text">2.3.1 initMultipartResolver方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-2-initLocaleResolver-方法"><span class="nav-number">3.3.2.</span> <span class="nav-text">2.3.2 initLocaleResolver 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-3-initThemeResolver方法"><span class="nav-number">3.3.3.</span> <span class="nav-text">2.3.3 initThemeResolver方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-4-initHandlerMappings方法"><span class="nav-number">3.3.4.</span> <span class="nav-text">2.3.4 initHandlerMappings方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-5-initHandlerAdapters方法"><span class="nav-number">3.3.5.</span> <span class="nav-text">2.3.5 initHandlerAdapters方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-6-initHandlerExceptionResolvers方法"><span class="nav-number">3.3.6.</span> <span class="nav-text">2.3.6 initHandlerExceptionResolvers方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-7-initRequestToViewNameTranslator方法"><span class="nav-number">3.3.7.</span> <span class="nav-text">2.3.7 initRequestToViewNameTranslator方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-8-initViewResolvers方法"><span class="nav-number">3.3.8.</span> <span class="nav-text">2.3.8 initViewResolvers方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-9-initFlashMapManager方法"><span class="nav-number">3.3.9.</span> <span class="nav-text">2.3.9 initFlashMapManager方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-10-DispatcherServlet初始化方法中的默认值"><span class="nav-number">3.3.10.</span> <span class="nav-text">2.3.10 DispatcherServlet初始化方法中的默认值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-11-小结"><span class="nav-number">3.3.11.</span> <span class="nav-text">2.3.11 小结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-DispatcherServlet处理请求分析"><span class="nav-number">3.4.</span> <span class="nav-text">2.4 DispatcherServlet处理请求分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-1-doService方法"><span class="nav-number">3.4.1.</span> <span class="nav-text">2.4.1 doService方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-2-doDispatch方法"><span class="nav-number">3.4.2.</span> <span class="nav-text">2.4.2 doDispatch方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-3-render方法"><span class="nav-number">3.4.3.</span> <span class="nav-text">2.4.3 render方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-4-小结"><span class="nav-number">3.4.4.</span> <span class="nav-text">2.4.4 小结</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-1/';
          this.page.identifier = '2018/08/12/learn-springmvc-code-1/';
          this.page.title = 'SpringMVC 解毒1';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
